#!/bin/sh
SHELL_ACTION=$1
APP_DIR=$2
APP_MAIN_CLASS=$3
DEBUG_PORT=$4
SERVICE_ENV=$5
SERVICE_CONFIG_SERVICE_URL=$6

JAVA_HOME_PATH=/usr/local/java/1.8/
MVN_HOME=/usr/local/maven/
JAVA_OPTS_DEBUG=""
SERVICE_OPTS_CONFIG=""

usage() {
    echo "Usage: sh service.sh [restart|start|stop|check]"
    exit 1
}

kills(){
    tpid=`ps -ef|grep ${APP_MAIN_CLASS}|grep -v grep|grep -v kill|awk '{print $2}'`
    if [[ ${tpid} ]]; then
        echo 'Kill Process!'
        kill -9 $tpid
    fi
}

start(){
	#verify parm
	if [ ! -n "$SERVICE_ENV" ]; then
		echo "env is requisite!"
		exit 1
	else
		echo "env:${SERVICE_ENV}"
	fi

	#debug opts
	if [ "${DEBUG_PORT}" != "0" ]; then
		JAVA_OPTS_DEBUG="-Xdebug -Xrunjdwp:transport=dt_socket,address=${DEBUG_PORT},server=y,suspend=n"
	else
		echo "D'T NEED DEBUG!"
	fi
	#debug opts
	if [ -n "$SERVICE_CONFIG_SERVICE_URL" ]; then
		SERVICE_OPTS_CONFIG="-Dspring.cloud.config.profile=${SERVICE_ENV} -Dspring.cloud.config.uri=${SERVICE_CONFIG_SERVICE_URL}"
	else
		echo "D'T NEED CONFIG SERVICE!"
	fi

	#set java home
	export JAVA_HOME=${JAVA_HOME_PATH}
	#jenkins config
	export JENKINS_NODE_COOKIE=dontKillMe


	JAVA_OPTS=" ${SERVICE_OPTS_CONFIG} ${JAVA_OPTS_DEBUG}"

	JAVA_MEM_OPTS=""
	BITS=`java -version 2>&1 | grep -i 64-bit`
	if [ -n "$BITS" ]; then
		JAVA_MEM_OPTS=" -server -Xmx2g -Xms2g -Xmn256m -Xss256k -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:LargePageSizeInBytes=128m -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 "
	else
		JAVA_MEM_OPTS=" -server -Xms1g -Xmx1g -XX:SurvivorRatio=2 -XX:+UseParallelGC "
	fi
	
    rm -f ${APP_DIR}/tpid
    nohup ${JAVA_HOME}/bin/java ${JAVA_OPTS} ${JAVA_MEM_OPTS} -cp ${APP_DIR}/jar/.:${APP_DIR}/jar/lib/*
    "$APP_MAIN_CLASS" >${APP_DIR}/logs/service.log &
    echo $! > ${APP_DIR}/tpid
    echo "Start Success!"
}

stop(){
	if [ -f "${APP_DIR}/tpid" ];then
		tpid=$(cat ${APP_DIR}/tpid)
		echo "tpid-${tpid}"
		if  [ -n "${tpid}" ]; then
			echo 'Stop Process...'
			kill -9 ${tpid}
		fi
	fi
}


check(){
    tpid=`ps -ef|grep ${APP_MAIN_CLASS}|grep -v grep|grep -v kill|awk '{print $2}'`
    if [[ tpid ]]; then
        echo 'App is running.'
    else
        echo 'App is NOT running.'
    fi
}

case "${SHELL_ACTION}" in
    "start")
        start
        ;;
    "stop")
        stop
        ;;
    "restart")
        stop
        start
        ;;
    "check")
        check
        ;;
    *)
        usage
        ;;
esac
